<script setup>
import { ref, onMounted ,computed} from "vue"
import {getAddressBookDefault, queryAddressBookList} from "@/apis/addressBookApi.js";
import {useCartStore} from "@/stores/cartStore.js";
import {submitOrderSubmit} from "@/apis/orderApi.js";
import {useRouter} from "vue-router";
import AddressBook from "@/views/AddressBook/index.vue"
const router=useRouter()

// 标签数组：索引0-家，1-公司，2-其他
const label = ref(["家", "学校","公司", "其他"]);
const defaultAddress = ref({
  "id": 5,
  "userId": 2,
  "consignee": "东的",
  "phone": "13111111111",
  "sex": "0",
  "provinceCode": "12",
  "provinceName": "天津市",
  "cityCode": "1201",
  "cityName": "市辖区",
  "districtCode": "120101",
  "districtName": "和平区",
  "detail": "大学城美丽墅",
  "label": "1", // 后端默认传1-3
  "isDefault": 1
});

// 获取默认地址数据
const getDefaultAddress = async () => {
  try {
    const res = await getAddressBookDefault();
    console.log("获取到的默认地址：", res.data);

    // 处理label值：后端1-3对应数组0-2
    const labelValue = Number(res.data.label);
    if (labelValue >= 1 && labelValue <= 3) {
      defaultAddress.value = res.data;
    } else {
      // 处理无效的label值，默认使用"其他"
      const validAddress = { ...res.data, label: "3" };
      defaultAddress.value = validAddress;
    }
  } catch (error) {
    console.error("获取默认地址失败：", error);
  }
}

onMounted(() => {
  getDefaultAddress();
})
const cartStore = useCartStore()

// 计算总价
const totalPrice = computed(() => {
  return cartStore.cartList.reduce((total, item) => {
    return total + item.amount * item.number;
  }, 0);
});

const orderSubmit=ref({})

const pay=async ()=>{
  orderSubmit.value={
    "addressBookId": defaultAddress.value.id,
    "payMethod": 0,
    "remark": "快递小哥一路顺风",
    "estimatedDeliveryTime": "2025-09-25 21:01:01",
    "deliveryStatus": 0,
    "tablewareNumber": 0,
    "tablewareStatus": 0,
    "packAmount": 0,
    "amount":totalPrice.value,
  }

  const res= await submitOrderSubmit(orderSubmit.value);
  console.log(res.data);
  if(res.data.orderNumber){

    router.push({
      path:"/pay",
      query:{"id": res.data.id}
    },)
  }

}

const addressBookList =ref([])
const getAddressBookList = async () => {
  const res=await queryAddressBookList();
  console.log(res.data)
  addressBookList.value=res.data;
}
const showDialog=ref(false);
const changeAddress=()=>{
  showDialog.value = true;
  getAddressBookList();
}
const showDialogForAdd=ref(false);
const addAddress=()=>{
  showDialogForAdd.value = true;
}
const switchAddress=(item)=>{
  console.log(item)
  defaultAddress.value = item;
}
const closeDialog=()=>{
  showDialog.value = false;
  showDialogForAdd.value = false;
}

</script>

<template>
  <div class="container">
    <div class="hearder">
      <RouterLink to="/" style="text-decoration: none; color: #333;"> <span>< </span></RouterLink>
      <span>提交订单</span>
      <span><RouterLink to="/" style="text-decoration: none; color: #333;">分享到朋友圈</RouterLink></span>
    </div>
    <div class="address-card">
      <div class="address-header">
        <!-- 后端1-3对应数组0-2，所以减1 -->
        <h6 class="address-label">{{ label[Number(defaultAddress.label) - 1] }}</h6>
         <span v-if="defaultAddress.isDefault" class="default-tag" ><RouterLink to="/addressBook" style="text-decoration: none; color: #333;">切换地址 </RouterLink></span>
        <span>
          <el-button type="primary" @click="changeAddress">切换地址</el-button>
          <el-button type="primary" @click="addAddress">添加地址</el-button>
        </span>
      </div>
      <div class="address-info">
        <p class="consignee">
          {{ defaultAddress.consignee }}
          <span class="phone">{{ defaultAddress.phone }}</span>
        </p>
        <p class="address-detail">
        {{ defaultAddress.provinceName }} {{ defaultAddress.cityName }} {{ defaultAddress.districtName }} {{ defaultAddress.detail }}
        </p>
      </div>
    </div>

    <div class="order-detail">
      <h4>东东大酒店</h4>
      <ul>
        <li v-for="item in cartStore.cartList" :key="item.id">
          <img :src="item.image" style="width: 100px; height: 100px; border-radius: 5px" />
          <div class="item-info">
            <span>{{ item.name }}</span>
            <span>X {{ item.number }}</span>
          </div>
          <div class="item-count">
            <span> ¥{{ item.amount }}</span>
          </div>
        </li>
      </ul>
      <div class="package">
        <span>打包费</span>
        <span>¥5</span>
      </div>
      <div  class="send">
        <span>配送费</span>
        <span>¥10</span>
      </div>
      <p class="all">合计 ¥{{totalPrice+5+10}}</p>
    </div>
    <div class="note">
      备注
      <el-button type="primary" @click="pay">提交订单</el-button>
    </div>
  </div>
  <!--切换地址-->
  <el-dialog v-model="showDialog" title="切换收货地址" width="5rem" center>
    <div class="addressWrapper">
     <div :class="{active:defaultAddress.id===item.id}" @click="switchAddress(item)" v-for="item in addressBookList"  v-bind:key="item.id">
       <ul class="address-list">
          <li> <span>收货人：{{item.consignee}}</span></li>
           <li><span>联系电话：{{item.phone}}</span></li>
           <li> <span>收货地址：{{item.provinceName+item.cityName+item.districtName+item.detail}}</span></li>
           <li> <span>{{item.isDefault===0?"默认地址":"备用地址"}}</span></li>
       </ul>
     </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="closeDialog">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!--添加地址-->
  <el-dialog v-model="showDialogForAdd" title="新增地址" center>
    <div class="addressWrapper">
      <ul>
        <li>
          <!--        { "id": 4, "userId": 2, "consignee": "东东", "phone": "13883155245", "sex": "0", "provinceCode": "50", "provinceName": "重庆市", "cityCode": "5001", "cityName": "市辖区", "districtCode": "500106", "districtName": "沙坪坝区", "detail": "大学城美丽墅", "label": "2", "isDefault": 0 }
               -->

          <p/> <span>收货人：<el-text></el-text></span>
          <p/><span>联系电话：<el-text></el-text></span>
          <p/> <span>收货地址：<el-text></el-text></span>
          <p/> <span>是否为默认地址：<el-radio >
         <el-radio-button/>是
         <el-radio-button/>否
        </el-radio></span>
        </li>

      </ul>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button>取消</el-button>
        <el-button type="primary" @click="closeDialog">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.address-list{
  list-style: none;
}
.active{
  background: #1dc779;
}
/*.container {
  display: flex;
  flex-direction: column;
  padding: 16px;
  gap: 16px;
}*/
.container {
  max-width: 600px;
  min-width: 200px;
  display: flex;
  flex-direction: column;
  margin: 0 auto;
  padding: 16px;
  border: 1px solid #ccc;
  border-radius: 15px;
}

.hearder {
  display: flex;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  width: 100%;
  max-width: 600px;
  justify-content: space-between;
  text-decoration: none;/*无下划线*/
  text-align: center; /*文字居中*/
}

.address-card {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  width: 100%;
  max-width: 600px;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.address-label {
  margin: 0;
  color: #666;
  font-size: 14px;
  padding: 2px 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.default-tag {
  font-size: 12px;
  color: #fff;
  background-color: #ff4d4f;
  padding: 2px 6px;
  border-radius: 4px;
}

.address-info {
  color: #333;
}

.consignee {
  margin: 0 0 8px 0;
  font-weight: 500;
}

.phone {
  margin-left: 16px;
  color: #666;
  font-weight: normal;
}

.address-detail {
  margin: 0;
  line-height: 1.5;

}

.order-detail{
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  width: 100%;
  max-width: 600px;
}
.order-detail ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.order-detail li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.item-info {
  display: flex;
  flex-direction: column;
}

.item-count {
  display: flex;
  align-items: center;
}

.item-count button {
  width: 24px;
  height: 24px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
}
.order-detail p{
  text-align: match-parent;
}
.order-detail .all{
  text-align: right;
}
.order-detail .package {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.order-detail .send {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.note {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  width: 100%;
  max-width: 600px;
}
</style>
